#include "affairs.h"
#include "connection.h"
#include "qcalendardialog.h"
#include "adddialog.h"
#include "ui_affairs.h"
#include <QDate>
#include <QUuid>

affairs::affairs(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::affairs)
{
    ui->setupUi(this);

    QDate date = QDate::currentDate();
    this->date = date.toString("yyyy-MM-dd");

    //定义数据模型
    model = new QSqlTableModel(this, Connection::getDatabase());
    model->setTable("affairs");
    model->setEditStrategy(QSqlTableModel::OnRowChange);
    model->select();

    // 设置编辑策略
    ui->tableView->setModel(model);
    ui->tableView->setColumnHidden(0, true);
    ui->tableView->setColumnHidden(1, true);
    ui->tableView->setColumnHidden(3, true);
    ui->tableView->setColumnHidden(4, true);

    QRect rect = geometry();
    ui->tableView->verticalHeader()->setDefaultSectionSize(rect.height() / 5);

    UpdateView();
}

affairs::~affairs()
{
    delete ui;
}

void affairs::on_calendarButton_clicked()
{
    QCalendarDialog calender;
    calender.exec();

    if (QCalendarDialog::Ok == calender.getState())
    {
        QDate date = calender.selectedDate();
        this->date = date.toString("yyyy-MM-dd");
        UpdateView();
    }
}

void affairs::on_addButton_clicked()
{
    AddDialog add;
    if (add.exec() == QDialog::Accepted)
    {
        int row = model->rowCount();//获得表的行数
        model->insertRow(row); //添加一行
        model->setData(model->index(row,0),QUuid::createUuid().toString());
        model->setData(model->index(row,2),add.getText());
        model->submit();
        UpdateView();
    }
}

void affairs::on_deleteButton_clicked()
{
    QModelIndex index = ui->tableView->currentIndex();
    if (index.isValid())
    {
        model->removeRow(index.row(), index.parent());
        model->submit();
        UpdateView();
    }
}

void affairs::UpdateView()
{
    model->setFilter(QObject::tr("addTime like '%1 \%'").arg(this->date));
}

void affairs::on_exitButton_clicked()
{
    qApp->quit();
}
